package cn.eu.mqtt.handler;

import cn.eu.mqtt.model.req.HeartbeatReq;
import cn.eu.mqtt.model.req.RegisterReq;
import cn.eu.mqtt.model.res.HeartbeatRes;
import cn.eu.mqtt.model.res.RegisterRes;
import cn.hutool.core.thread.ThreadUtil;
import com.mos.iot.mqtt.MqttClientManager;
import com.mos.iot.mqtt.listener.MqttTopicMessage;
import com.mos.iot.mqtt.listener.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MessageHandler {

    @MqttOutput(topic = "om/server/res/register/{deviceCode}")
    @MqttInput(topics = "om/client/req/register/{deviceCode}")
    public RegisterRes register(@MqttTopic String topic,
                                @MqttTopicPath String deviceCode,
                                @MqttPayload RegisterReq registerReq,
                                @TopicMessage MqttTopicMessage mqttTopicMessage) {
        log.info("收到设备注册消息: {}", deviceCode);
        RegisterRes registerRes = RegisterRes.builder().operationId(registerReq.getOperationId()).build();
        ThreadUtil.execute(() -> {
            Object res = MqttClientManager.syncPublish(MqttTopicMessage
                            .builder()
                            .topic("om/server/res/register/" + deviceCode)
                            .payload(registerRes).build(),
                    "123456", 1);
        });
        return null;
    }

    @MqttOutput(topic = "om/server/res/heartbeat/{deviceCode}")
    @MqttInput(topics = "om/client/req/heartbeat/{deviceCode}")
    public HeartbeatRes heartbeat(@MqttTopic String topic,
                                  @MqttTopicPath String deviceCode,
                                  @MqttPayload HeartbeatReq heartbeatReq) {
        log.info("收到设备心跳消息: {}", deviceCode);
        return HeartbeatRes.builder().build();
    }

}
